#include <iostream>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include"server.h"
using namespace std;

int init_server(short port)
{
// 忽略SIGPIPE信号
signal(SIGPIPE, SIG_IGN);
// 1.创建套接字
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
perror("socket error");
return -1;
}
int on = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
// 2.邦定IP地址和端口号
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = inet_addr("0.0.0.0");
int ret = bind(listenfd, (sockaddr*)&sin, sizeof(sin));
if (ret < 0) {
perror("bind error");
close(listenfd);
return -1;
}
// 3.监听
ret = listen(listenfd, 5);
if (ret < 0) {
perror("listen error");
close(listenfd);
return -1;
}
return listenfd;
}
int tcp_comm(int connectfd)
{
// 获取编码后的图像数据
string image = encode_image();
// 格式化图像数据长度为6个字节，不足6个字节前面补0
char size[10] = {0};
sprintf(size, "%06ld", image.size());
cout << "size:" << size << endl;
// 拼接字符串(图像数据长度#图像数据)
string msg = string(size) + "#" + image;
// 发送一张图片
int ret = send(connectfd, msg.data(), msg.size(), 0);
if (ret < 0) {
perror("send error");
return -1;
}
return 0;
}
void* handle_client(void *arg)
{
int connectfd = *(int *)arg;
// 客户端和服务器通信
while (1) {
int ret = tcp_comm(connectfd);
 send(connectfd, retMe.c_str(), retMe.length(), 0);
if (ret < 0) {
break;
}
usleep(20000);
}
// 6.关闭套接字
close(connectfd);
return NULL;
}
int main()
{
// 打开摄像头
if (!open_camera()) {
cout << "open_camera error" << endl;
return -1;
}
cout << "Open camera successfully." << endl;
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, collect_image, NULL);
pthread_create(&tid2, NULL, detect_face, NULL);
// 初始化服务器
int listenfd = init_server(6000);
// 与TCP客户端通信
while (1) {
// 4.接受客户端的连接
int connectfd = accept(listenfd, NULL, NULL);
if (connectfd < 0) {
perror("accept error");
break;
}
cout << "accept ok" << endl;
pthread_t tid;
pthread_create(&tid, NULL, handle_client, &connectfd);
pthread_detach(tid);
}
return 0;
}

